import classnames from 'classnames'
import { Dialog, Divider, NavBar, SearchBar } from 'antd-mobile'

import Icon from '@/component/Icon'
import styles from './index.module.scss'
import { useNavigate } from 'react-router-dom'
import { useState } from 'react'
import { useDebounceFn } from 'ahooks'
import { useAppDispatch, useAppSelector } from '@/store/hook'
import {
  getSuggestionAction,
  removeAllHistoryAction,
  removeHistoryAction,
  removeSuggestionAction,
  setHistoryAction
} from '@/store/reducers/search'
const SearchPage = () => {
  // redux
  const dispatch = useAppDispatch()
  const { suggestion, histories } = useAppSelector(state => state.searcher)
  // 跳转首页
  const navigate = useNavigate()
  // 输入框受控
  const [value, setValue] = useState('')
  // 防抖
  const { run } = useDebounceFn(
    async v => {
      if (v) {
        await dispatch(getSuggestionAction(v))
        setHistoryShow(false)
      } else {
        dispatch(removeSuggestionAction())
        setHistoryShow(true)
      }
    },
    { wait: 200 }
  )
  // 搜素框值发生改变
  const onChange = (v: string) => {
    setValue(v)
    run(v)
  }
  // 设置高亮
  const hightLight = (v: string) => {
    return v.replace(new RegExp(value, 'gi'), match => `<span>${match}</span>`)
  }
  // 控制历史记录
  const [historyShow, setHistoryShow] = useState(true)

  // 搜索并存缓存
  const onSearch = async (type:'search'|'click',v: string) => {

    await dispatch(setHistoryAction(v))
    navigate({
      pathname:'/search/result',
      search:`q=${v}`
    })
  }
  // 退回首页
  const onBack = async () => {
    // 如果有建议
    if (suggestion.length || value) {
      // 清空
      await dispatch(removeSuggestionAction())
      setValue('')
      setHistoryShow(true)
    } else {
      navigate('/home')
    }
  }
  // 点击历史记录
  const HisClick = (v: string) => {
    onChange(v)
  }
  // 清除历史记录
  const removeHistory = (type: 'all' | 'single', v?: string) => {
    // 清除全部
    if (type === 'all') {
      Dialog.confirm({
        confirmText: '确认',
        content:'确认清空吗',
        async onConfirm () {
          await dispatch(removeAllHistoryAction())
        }
      })
    } else if (type === 'single') {
      Dialog.confirm({
        confirmText: '确认',
        content:'确认删除吗',
        async onConfirm () {
          await dispatch(removeHistoryAction(v!))
        }
      })
      
    }
  }
  return (
    <div className={styles.root}>
      <NavBar
        className='navbar'
        onBack={onBack}
        right={<span className='search-text' onClick={()=>onSearch('click',value)}>搜索</span>}
      >
        <SearchBar
          value={value}
          onChange={onChange}
          onSearch={(v)=>onSearch('search',v)}
          placeholder='请输入关键字搜索'
        />
      </NavBar>

      {/* 历史记录区域 */}
      {historyShow && (
        <div
          className='history'
          style={{
            display: historyShow ? 'block' : 'none'
          }}
        >
          <div className='history-header'>
            <span>搜索历史</span>
            <span onClick={() => removeHistory('all')}>
              <Icon type='iconbtn_del' />
              清除全部
            </span>
          </div>
          {histories &&
            histories.map((v, i) => {
              return (
                <div
                  className='history-list'
                  key={i}
                  onClick={() => HisClick(v)}
                >
                  <span className='history-item'>
                    <span className='text-overflow'>{v}</span>
                    <Icon
                      type='iconbtn_essay_close'
                      onClick={() => removeHistory('single', v)}
                      stopPropagation={true}
                    />
                  </span>
                </div>
              )
            })}
        </div>
      )}
      {/* 联想搜索区域 */}
      <div className={classnames('search-result', !historyShow ? 'show' : '')}>
        {suggestion.length ?
          suggestion.map((v, i) => {
            return (
              <div className='result-item' key={i}>
                <Icon type='iconbtn_search' />
                <div
                  className='result-value text-overflow'
                  dangerouslySetInnerHTML={{ __html: hightLight(v) }}
                ></div>
              </div>
            )
          })
          :
          <Divider>暂无建议</Divider>
        }
      </div>
    </div>
  )
}

export default SearchPage
